const app = getApp()

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 获取新的token
function refreshTokenFun(refreshToken) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: app.http + 'token' + '?refreshToken=' + refreshToken,
      data: {},
      method: 'PUT',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log("获取新的tokensuc返回", res.data.code)
        if (res.data.code == 200) {
          app.globalData.tokenMap = res.data.data;
          wx.setStorage({
            key: 'tokenMap',
            data: res.data.data,
          })
        }
        resolve(res);
      },
      fail: function (err) {
        // console.log("获取新的tokenfail返回", err)
        reject("系统异常，请重试！")
      }
    })
  })
}

// 手机号登录
function wxLoginFun() {
  return new Promise(function (resolve, reject) {
    var postData = {
      wxOpenid: app.globalData.codeData.openid,
      wxUnionid: app.globalData.codeData.unionid,
      mobile: app.globalData.loginUserObj.mobile,
      wxNickname: app.globalData.loginUserObj.name,
      wxHeadimgurl: app.globalData.loginUserObj.mainPic,
    }
    wx.request({
      url: app.http + 'user/wloginletPlusHys',
      data: postData,
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log("登录返回", res)
        resolve(res);
        if (res.data.code == 200) {
          wx.setStorage({
            key: 'tokenMap',
            data: res.data.data.tokenMap,
          })
          wx.setStorage({
            key: 'loginUserObj',
            data: res.data.data.user,
          })
          app.globalData.tokenMap = res.data.data.tokenMap;
          app.globalData.loginUserObj = res.data.data.user;
        }
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
}

// 解析手机号
function letPhoneNumFun(encryptedData, iv) {
  return new Promise(function (resolve, reject) {
    var phoneData = {
      "appId": app.appid,
      "encryptedData": encryptedData,
      "iv": iv,
      "sessionKey": app.globalData.codeData.session_key
    }

    wx.request({
      url: app.http + 'wechat/letDecode',
      data: phoneData,
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (resPhone) {
        console.log("解析手机号成功返回", resPhone)
        if (resPhone.data.code == 200) {
          var phoneNum = resPhone.data.data;
          var postData = {
            wxOpenid: app.globalData.codeData.openid,
            wxUnionid: app.globalData.codeData.unionid,
            mobile: phoneNum,
            wxNickname: app.globalData.userInfo.nickName,
            wxHeadimgurl: app.globalData.userInfo.avatarUrl,
          }
          console.log("6666+postData", postData)
          wx.request({
            url: app.http + 'user/wloginletPlusHys',
            data: postData,
            method: 'POST',
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: function (resLogin) {
              console.log("登录返回", resLogin)
              resolve(resLogin);
              if (resLogin.data.code == 200) {
                wx.setStorage({
                  key: 'tokenMap',
                  data: resLogin.data.data.tokenMap,
                })
                wx.setStorage({
                  key: 'loginUserObj',
                  data: resLogin.data.data.user,
                })
                app.globalData.tokenMap = resLogin.data.data.tokenMap;
                app.globalData.loginUserObj = resLogin.data.data.user;
              }
            },
            fail: function (err) {
              reject(err)
            }
          })
        }
      },
      fail: function (err) {
        reject("系统异常，请重试！")
      }
    })
  })
}

// 上传文件
function upFileFun(tempFilePath) {
  var userId = "";
  if (app.globalData.loginUserObj != null) {
    userId = app.globalData.loginUserObj.id;
  }
  return new Promise(function (resolve, reject) {

    wx.uploadFile({
      // url: app.http + 'wechat/letUploadOssPlus',
      url: app.http + 'file/uploadFileOss' + '?userId=' + userId,
      filePath: tempFilePath,
      name: 'file',
      header: {
        'APP-User-Token': app.globalData.tokenMap.access_token,
      },
      success: function (res) {
        // console.log("上传文件返回", res)
        // if (res.statusCode == 200){
        //   var datas = JSON.parse(res.data);
        //   console.log("上传文件解析", datas)
        //   resolve(datas);
        // }
        resolve(res);
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
}

module.exports = {
  formatTime: formatTime,
  refreshTokenFun: refreshTokenFun,
  wxLoginFun: wxLoginFun,
  letPhoneNumFun: letPhoneNumFun,
  upFileFun: upFileFun
}
